package com.acmedcare.framework.exchange.center.endpoint.service;

import com.acmedcare.framework.exchange.center.common.ConvertUtils;
import com.acmedcare.framework.exchange.center.common.Page;
import com.acmedcare.framework.exchange.center.entity.bean.TaskDetail;
import com.acmedcare.framework.exchange.center.entity.dto.TaskHistoryQueryDto;
import com.acmedcare.framework.exchange.center.entity.dto.TaskHistoryViewDto;
import com.acmedcare.framework.exchange.center.repository.TaskDetailRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class TaskHistoryService {

  private final TaskDetailRepository detailRepository;

  public TaskHistoryService(
      TaskDetailRepository detailRepository) {
    this.detailRepository = detailRepository;
  }

  public Page<TaskHistoryViewDto> getList(TaskHistoryQueryDto queryDto) {

    QueryWrapper<TaskDetail> queryWrapper = new QueryWrapper<>();

    if (!StringUtils.isEmpty(queryDto.getName())) {

      queryWrapper.like("name", queryDto.getName());
    }

    if (queryDto.getBeginTime() != null) {

      queryWrapper.gt("execute_time", queryDto.getBeginTime());
    }

    if (queryDto.getEndTime() != null) {

      queryWrapper.lt("execute_time", queryDto.getEndTime());
    }

    queryWrapper.orderByDesc("execute_time");
    PageHelper.startPage(queryDto.getCurrPage(), queryDto.getSize());
    List<TaskDetail> taskDetails = detailRepository.selectList(queryWrapper);
   // PageInfo<TaskDetail> pageInfo=new PageInfo<>(taskDetails);
    if (!taskDetails.isEmpty()) {

      Page<TaskDetail> detailPage = ConvertUtils.convertPage(taskDetails);
      List<TaskHistoryViewDto> list = detailPage.getList().stream().map(o -> {

        TaskHistoryViewDto viewDto = ConvertUtils.convertType(o, TaskHistoryViewDto.class);
        return viewDto;
      }).collect(Collectors.toList());

      Page<TaskHistoryViewDto> viewDtoPage = ConvertUtils.convertPage(list);
      viewDtoPage.setNum(detailPage.getNum());
      viewDtoPage.setSize(detailPage.getSize());
      viewDtoPage.setRowCount(detailPage.getRowCount());
      viewDtoPage.setPageCount(detailPage.getPageCount());
      return viewDtoPage;
    }

    return null;
  }

  public TaskDetail getDetail(Long taskDetailId) {

    return detailRepository.selectById(taskDetailId);
  }
}
